from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
from fastadmin.utils.Utils import Utils
utils = Utils()
class BaseMiddleware(BaseHTTPMiddleware):

    def __init__(self,app):
        super().__init__(app)
        self.middleware = {}
        self.module = 'index'
    async def dispatch(self, request: Request, call_next):
        # print(request.url,request.base_url,'uuuuuuuuuuuuuuuuuu')
        module = utils.get_url_2_module(request.url,request.base_url)
        controller = utils.get_url_2_controller(request.url,request.base_url)
        action = utils.get_url_2_action(request.url,request.base_url)
        print(module,controller,action)
        if module == self.module:
            if self.middleware != {}:
                print(self.middleware)
                if controller in self.middleware:
                    if isinstance(self.middleware[controller],dict):
                        has = False
                        for key,value in self.middleware[controller].items():
                            if key == action:
                                response = await value(request,call_next)
                                has = True
                                # print(value,'value')
                            else:
                                pass
                        if has == False:
                            if 'index' in self.middleware[controller]:
                                response = await self.middleware[controller]['index'](request,call_next)
                            else:
                                response = await call_next(request)
                            # response = await call_next(request)
                            # if self.middleware[controller].has_key('index'):
                            #     response = await self.middleware[controller]['index'](request,call_next)
                            # else:
                            #     response = await call_next(request)
                    else:
                        response = await self.middleware[controller](request,call_next)
                        # print(self.middleware[controller],'objct')
                # response = await call_next(request)
            else:
                response = await call_next(request)
        else:
            response = await call_next(request)
        return response